//  axios二次封装
import config from "@/config";
import axios from "axios";

class HttpRequest {
    constructor() {
        // 这里可以增加实例属性 后台接口的路径 开发模式和生产模式不一样
        this.baseURL = config;
        this.timeout = 300000; // 3秒后请求超时
    }
    setInterceptors(instance) {
        instance.interceptors.request.use((config) => {
            // 一般增加一些token属性等
            config.headers.Authorization = localStorage.getItem("token");
            return config;
        });
        instance.interceptors.response.use(
            (res) => {
                setTimeout(() => {
                }, 200);
                const status = res.data.status;
                switch (status) {
                    case 200: {
                        return Promise.resolve(res.data);
                    }
                    case 401: {
                        localStorage.removeItem("token");
                        localStorage.removeItem("userInfo");
                        let r = `?logout=1&source=1&returnUrl=${encodeURIComponent(window.location.href)}`
                        window.location.replace(process.env.VUE_APP_SSO_HOME_URL + r)
                        return Promise.reject(res.data);
                    }
                    default: {
                        return Promise.reject(res.data);
                    }
                }
            },
            (err) => {
                setTimeout(() => {
                }, 200);
                switch (err.response.status) {
                    case "401":
                        break;
                }
                return Promise.reject(err);
            }
        );
    }

    mergeOptions(options) {
        return {baseURL: this.baseURL, timeout: this.timeout, ...options};
    }

    request(options) {
        // 每个实例的拦截器和其他人无关，如果使用全局的实例，我想给每次请求单独配置拦截器就所不到
        const instance = axios.create(); // 创建axios实例
        this.setInterceptors(instance);
        const opts = this.mergeOptions(options);
        return instance(opts);
    }

    get(url, data) {
        return this.request({
            method: "get",
            url,
            data: data,
        });
    }
    post(url, data) {
        return this.request({
            method: "post",
            url,
            data: data,
        });
    }
}

export default new HttpRequest();